<?php
namespace cubox;

class Data{
    
    private array   $__data  = [];
    private string  $__path  = '';
    private bool    $__change = false;

    //缓存已经读取过的数据
    private static array $__cache = [];

    
    /**
     * @param string $path 文件路径
     * @param array $default 默认值
     */
    public function __construct($path)
    {
        $this->__path  =  $path;
        if (isset(self::$__cache[$path])){
            $this->__data = self::$__cache[$path];
        }else{
            $this->read();    
        }
    }

    public function __get($key){
        return $this->__data[$key] ?? null;
    }

    public function __set($key,$value){
        $this->__change =  true;
        $this->__data[$key] = $value;
    }

    public function __isset($name) 
    {
        return isset($this->__data[$name]);
    }

    public function __unset($name) 
    {
        $this->__change =  true;
        unset($this->__data[$name]);
    }

    public function __destruct()
    {
        if ($this->__change){
            $this->save();
        }
    }

    public function save(){
        if (function_exists('opcache_reset')) opcache_reset();

        if (!file_exists(dirname($this->__path))) mkdir(dirname($this->__path), 0777, true);

        return  file_put_contents($this->__path,"<?php\nreturn ".var_export($this->__data,true).";");
    }
    /**
     * 将内容以数组形式返回
     * @return array
     */
    public function toArray():array{
        return $this->__data;
    }


    public function setData(array $data){
        $this->__change =  true;
        $this->__data  =  $data;
    }


    /**
     * 是否为空
     * @return bool
     */
    public function empty():bool{
        return empty($this->__data);
    }

    public function exists($key):bool{
        return isset($this->__data[$key]);
    }

    public function del($key){
        $this->__change =  true;
        unset($this->__data[$key]);
    }

    public function clear(){
        $this->__change =  true;
        $this->__data  =  [];
    }

    /**
     * 读取文件内容
     * 
     * 不论是否已经有数据，都重新读取文件内容
     */
    public function read():Data{

        if (file_exists($this->__path)){
            
            try{
                $data =  require($this->__path);

                if (is_array($data)){
                    $this->__data  =  $data;
                }else{
                    $this->__data  =  [];
                }

                self::$__cache[$this->__path] = $this->__data;
                 
            }catch(\Exception $e){
                $this->__data  =  [];
            }
        }

        return $this;
        
    }
}